package com.cicdi.model;

import com.cicdi.util.Web3jUtil;
import com.platon.contracts.ppos.dto.resp.Proposal;
import com.platon.contracts.ppos.dto.resp.TallyResult;
import lombok.Data;

import java.math.BigInteger;

/**
 * @author haypo
 * @date 2021/3/9
 */
@Data
public class MyTallyResult {
    /**
     * 提案ID
     */
    private String proposalId;

    private String proposer;
    private String proposalType;
    private String piPid;
    private BigInteger submitBlock;
    private BigInteger endVotingBlock;
    private BigInteger newVersion;
    /**
     * 赞成票
     */
    private BigInteger yeas;
    /**
     * 反对票
     */
    private BigInteger nays;
    /**
     * 弃权票
     */
    private BigInteger abstentions;
    /**
     * 在整个投票期内有投票资格的验证人总数
     */
    private BigInteger accuVerifiers;
    /**
     * 状态
     */
    private String status;
    private String toBeCanceled;
    /**
     * （如果投票通过）生效块高（endVotingBlock + 20 + 4*250 < 生效块高 <= endVotingBlock + 20 + 10*250）
     */

    private BigInteger activeBlock;

    /**
     * 提交提案的验证人
     */
    private String verifier;
    /**
     * 参数模块
     */
    private String module;
    /**
     * 参数名称
     */
    private String name;
    /**
     * 参数新值
     */
    private String newValue;


    private MyTallyResult(Proposal proposal, TallyResult tallyResult) {
        this.proposalId = proposal.getProposalId();
        this.activeBlock = proposal.getActiveBlock();
        this.endVotingBlock = proposal.getEndVotingBlock();
        this.submitBlock = proposal.getSubmitBlock();

        this.proposalType = switch (proposal.getProposalType()) {
            case 1 -> "文本提案";
            case 2 -> "升级提案";
            case 3 -> "参数提案";
            default -> null;
        };

        if (tallyResult != null) {
            this.status = convertStatus(tallyResult.getStatus());
            this.nays = tallyResult.getNays();
            this.yeas = tallyResult.getYeas();
        } else {
            this.status = convertStatus(0);
            this.nays = BigInteger.ZERO;
            this.yeas = BigInteger.ZERO;
        }
    }

    public MyTallyResult(Proposal proposal) throws Exception {
        this(proposal, Web3jUtil.getTallyResult(proposal.getProposalId()));
    }

    /**
     * 1 投票中
     * 2 投票通过
     * 3 投票失败
     * 4 （升级提案）预生效
     * 5 （升级提案）生效
     * 6 被取消
     *
     * @param status
     * @return
     */
    private static String convertStatus(int status) {
        return switch (status) {
            case 1 -> "投票中";
            case 2 -> "投票通过";
            case 3 -> "投票失败";
            case 6 -> "被取消";
            case 5 -> "（升级提案）生效";
            case 4 -> "（升级提案）预生效";
            default -> "null";
        };
    }


}
